<template>
  <view class="login-container">
    <!-- Logo -->
    <view class="logo-container">
      <image class="logo" src="/static/logo/logo.png"></image>
    </view>

    <!-- 欢迎文本 -->
    <view class="welcome-text">
      <text class="welcome-title">{{
        isLoginMode ? "欢迎回来，请登录您的账号" : "注册新账号"
      }}</text>
    </view>

    <!-- 登录/注册表单 -->
    <view class="login-form">
      <!-- 用户名输入框（仅注册模式显示） -->
      <view class="input-group" v-if="!isLoginMode">
        <view class="input-container">
          <image class="input-icon" src="/static/svgs/user.svg"></image>
          <input
            class="input-field"
            type="text"
            placeholder="请输入用户名"
            v-model="username"
          />
        </view>
      </view>

      <!-- 账号输入框 -->
      <view class="input-group">
        <view class="input-container">
          <image class="input-icon" src="/static/svgs/user.svg"></image>
          <input
            class="input-field"
            type="text"
            placeholder="请输入账号"
            v-model="account"
          />
        </view>
      </view>

      <!-- 密码输入框 -->
      <view class="input-group">
        <view class="input-container">
          <image class="input-icon" src="/static/svgs/lock.svg"></image>
          <input
            class="input-field"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            v-model="password"
          />
          <view class="password-toggle" @click="togglePassword">
            <image
              class="toggle-password"
              :src="
                showPassword
                  ? '/static/svgs/browse-off.svg'
                  : '/static/svgs/browse.svg'
              "
            ></image>
          </view>
        </view>
      </view>

      <!-- 记住密码（仅登录模式显示） -->
      <view class="remember-password" v-if="isLoginMode">
        <view class="checkbox-container" @click="toggleRemember">
          <view class="checkbox" :class="{ checked: rememberPassword }">
            <image
              v-if="rememberPassword"
              class="check-icon"
              src="/static/svgs/confirm.svg"
            ></image>
          </view>
        </view>
        <text class="remember-text">记住密码</text>
      </view>

      <!-- 登录/注册按钮 -->
      <button class="login-button" @click="isLoginMode ? login() : register()">
        {{ isLoginMode ? "登录" : "注册" }}
      </button>

      <!-- 切换模式链接 -->
      <view class="register-link">
        <text class="register-text">{{
          isLoginMode ? "还没有账号？" : "已有账号？"
        }}</text>
        <text class="register-action" @click="toggleMode">{{
          isLoginMode ? "立即注册" : "返回登录"
        }}</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { userApi } from "@/api";

// 响应式状态
const rememberPassword = ref(false);
const isLoginMode = ref(true); // 控制是登录模式还是注册模式
const showPassword = ref(false); // 控制密码显示/隐藏
const account = ref(""); // 账号
const password = ref(""); // 密码
const username = ref(""); // 用户名（注册时使用）

// 方法
const toggleRemember = () => {
  rememberPassword.value = !rememberPassword.value;
};

const toggleMode = () => {
  // 切换登录/注册模式，清空表单
  isLoginMode.value = !isLoginMode.value;
  account.value = "";
  password.value = "";
  username.value = "";
};

const togglePassword = () => {
  // 切换密码显示/隐藏
  showPassword.value = !showPassword.value;
};

const login = async () => {
  // 表单验证
  if (account.value.trim() === "") {
    uni.showToast({
      title: "请输入账号",
      icon: "none",
    });
    return;
  }

  if (password.value.trim() === "") {
    uni.showToast({
      title: "请输入密码",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({
      title: "登录中...",
    });

    // 调用登录接口
    const result = await userApi.login({
      account: account.value.trim(),
      password: password.value.trim(),
    });

    uni.hideLoading();

    // 登录成功处理
    if (result.success && result.code === "00000") {
      // 保存token和用户信息到本地存储
      uni.setStorageSync("zbox-token", result.data.token);
      uni.setStorageSync("zbox-userId", result.data.user.id);
      uni.setStorageSync("zbox-username", result.data.user.username);
      uni.setStorageSync("zbox-account", result.data.user.account);

      // 如果选择了记住密码，保存账号和密码
      if (rememberPassword.value) {
        uni.setStorageSync("zbox-rememberedAccount", account.value.trim());
        uni.setStorageSync("zbox-rememberedPassword", password.value.trim());
      } else {
        // 清除之前保存的账号密码
        uni.removeStorageSync("zbox-rememberedAccount");
        uni.removeStorageSync("zbox-rememberedPassword");
      }

      uni.showToast({
        title: "登录成功",
        icon: "success",
      });

      // 延迟跳转到首页
      setTimeout(() => {
        uni.reLaunch({
          url: "/pages/index/index",
        });
      }, 1500);
    } else {
      // 登录失败
      uni.showToast({
        title: result.msg || "登录失败",
        icon: "error",
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("登录失败:", error);
    uni.showToast({
      title: error.message || "登录失败，请稍后重试",
      icon: "error",
    });
  }
};

const register = async () => {
  // 表单验证
  if (username.value.trim() === "") {
    uni.showToast({
      title: "请输入用户名",
      icon: "none",
    });
    return;
  }

  if (account.value.trim() === "") {
    uni.showToast({
      title: "请输入账号",
      icon: "none",
    });
    return;
  }

  if (password.value.trim() === "") {
    uni.showToast({
      title: "请输入密码",
      icon: "none",
    });
    return;
  }

  // 简单的密码长度验证
  if (password.value.trim().length < 6) {
    uni.showToast({
      title: "密码长度不能少于6位",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({
      title: "注册中...",
    });

    // 调用注册接口
    const result = await userApi.register({
      username: username.value.trim(),
      account: account.value.trim(),
      password: password.value.trim(),
    });

    uni.hideLoading();

    // 注册成功处理
    if (result.success && result.code === "00000") {
      uni.showToast({
        title: "注册成功，请登录",
        icon: "success",
      });

      // 切换回登录模式，并保留账号信息方便登录
      setTimeout(() => {
        isLoginMode.value = true;
        username.value = ""; // 清空用户名
        // 保留账号和密码，方便用户直接登录
      }, 1500);
    } else {
      // 注册失败
      uni.showToast({
        title: result.msg || "注册失败",
        icon: "error",
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error("注册失败:", error);
    uni.showToast({
      title: error.message || "注册失败，请稍后重试",
      icon: "error",
    });
  }
};

// 页面加载时检查是否有记住的账号密码
const loadRememberedCredentials = () => {
  const rememberedAccount = uni.getStorageSync("zbox-rememberedAccount");
  const rememberedPassword = uni.getStorageSync("zbox-rememberedPassword");

  if (rememberedAccount && rememberedPassword) {
    account.value = rememberedAccount;
    password.value = rememberedPassword;
    rememberPassword.value = true;
  }
};

// 页面加载时执行
loadRememberedCredentials();
</script>

<style>
.login-container {
  padding: 40rpx;
  max-height: 100vh;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
}

.logo-container {
  margin-top: 80rpx;
  display: flex;
  justify-content: center;
}

.logo {
  width: 120rpx;
  height: 120rpx;
}

.welcome-text {
  margin-top: 60rpx;
  text-align: center;
}

.welcome-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
}

.login-form {
  margin-top: 80rpx;
}

.input-group {
  margin-bottom: 40rpx;
}

.input-container {
  position: relative;
  display: flex;
  align-items: center;
  border: 1px solid #e0e0e0;
  border-radius: 45rpx;
  padding: 0 30rpx;
  background-color: #ffffff;
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.input-container:focus-within {
  outline: none;
  border-color: #4361ee;
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.2);
}

.input-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 10rpx;
}

.input-field {
  flex: 1;
  height: 90rpx;
  font-size: 30rpx;
  background: transparent;
  border: none;
}

.toggle-password {
  width: 40rpx;
  height: 40rpx;
  color: #999999;
}

.password-toggle {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  padding: 10rpx;
}

.remember-password {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  margin-bottom: 60rpx;
}

.checkbox-container {
  display: flex;
  align-items: center;
}

.checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 1px solid #cccccc;
  border-radius: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.checkbox.checked {
  background-color: #0066cc;
  border-color: #0066cc;
}

.check-icon {
  width: 28rpx;
  height: 28rpx;
}

.remember-text {
  font-size: 26rpx;
  color: #666666;
  margin-left: 16rpx;
}

.login-button {
  height: 90rpx;
  background-color: #0066cc;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 45rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40rpx;
}

.register-link {
  display: flex;
  justify-content: center;
  margin-top: 30rpx;
}

.register-text {
  font-size: 28rpx;
  color: #666666;
}

.register-action {
  font-size: 28rpx;
  color: #0066cc;
  margin-left: 10rpx;
}
</style>
